﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Tnelab.Wpf
{
	public partial class WindowEx
	{
		public static readonly DependencyProperty IsMinimizeButtonProperty =
			DependencyProperty.RegisterAttached("IsMinimizeButton", typeof(bool), typeof(WindowEx), new(false, OnIsMinimizeButtonChanged));
		static void OnIsMinimizeButtonChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
		{

			var minimizeButtonElement = obj as UIElement;
			if (e.NewValue != e.OldValue)
			{
				var value = (bool)e.NewValue;
				if (value)
				{
                    minimizeButtonElement.PreviewMouseLeftButtonUp += MinimizeButtonElement_MouseLeftButtonUp;
				}
				else
				{
					minimizeButtonElement.PreviewMouseLeftButtonUp -= MinimizeButtonElement_MouseLeftButtonUp;
				}
			}
		}

        private static void MinimizeButtonElement_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
			var window = Window.GetWindow(sender as DependencyObject);
            if (window.WindowState != WindowState.Minimized)
            {
				window.WindowState = WindowState.Minimized;
            }
		}

		public static bool GetIsMinimizeButton(UIElement dpo)
		{
			return (bool)dpo.GetValue(IsMinimizeButtonProperty);
		}

		public static void SetIsMinimizeButton(UIElement dpo, bool value)
		{
			dpo.SetValue(IsMinimizeButtonProperty, value);
		}
	}
}
